package com.zzp.basepresenter.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.zzp.basepresenter.config.BaseConfig;
import com.zzp.basepresenter.ui.popwindows.LoadingProgressPopWindow;
import com.zzp.basepresenter.util.LoggerUtils;
import com.zzp.basepresenter.util.ToastUtils;

import java.util.Locale;

public abstract class BaseFragment extends Fragment {
    //记录最后一次点击时间
    private long lastClickTime;
    //视图是否已经初初始化
    protected boolean isInit = false;
    protected boolean isLoad = false;
    private View view;
    public float width, height;
    public Activity context;
    private LoadingProgressPopWindow loadingProgressPopWindow;

    //绑定butter
    public abstract void bindButter(View view);

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        changeLanguage(getActivity(), SharePreferenceUtils.getInstance(context).getString("CURRENT_LANGUAGE", "en"));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(setContentView(), container, false);
        bindButter(view);
        context = getActivity();
        isInit = true;
        /**初始化的时候去加载数据**/
        isCanLoadData(context, view);
        return view;
    }

    /**
     * 视图是否已经对用户可见，系统的方法
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData(context, view);
    }

    /**
     * 是否可以加载数据
     * 可以加载数据的条件：
     * 1.视图已经初始化
     * 2.视图对用户可见
     */
    private void isCanLoadData(Activity context, View view) {
        if (!isInit) {
            return;
        }
        if (getUserVisibleHint()) {
            lazyLoad(context, view);
            isLoad = true;
            width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
            height = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        } else {
            if (isLoad) {
                stopLoad(context, view);
            }
        }
    }

    /**
     * 视图销毁的时候讲Fragment是否初始化的状态变为false
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isInit = false;
        isLoad = false;
    }

    /**
     * 设置Fragment要显示的布局
     *
     * @return 布局的layoutId
     */
    protected abstract int setContentView();

    /**
     * 获取设置的布局
     *
     * @return
     */
    public View getContentView() {
        return view;
    }

    /**
     * 找出对应的控件
     *
     * @param id
     * @param <T>
     * @return
     */
    protected <T extends View> T findViewById(int id) {

        return (T) getContentView().findViewById(id);
    }

    /**
     * 当视图初始化并且对用户可见的时候去真正的加载数据
     */
    protected abstract void lazyLoad(Activity context, View view);

    /**
     * 当视图已经对用户不可见并且加载过数据，如果需要在切换到其他页面时停止加载数据，可以调用此方法
     */
    protected void stopLoad(Activity context, View view) {
    }

    /*
     *限制按钮多次点击一秒之内不能重复点击
     * */
    public boolean isSimpleClick() {
        boolean flag = false;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= BaseConfig.MIN_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = currentClickTime;
        return flag;
    }

    public void hideSoftKeyBoard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void showToast(String s) {
        ToastUtils.getInstance().ShortToast(context, s);
    }

    public void showToast(int res) {
        ToastUtils.getInstance().ShortToast(context, res);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (loadingProgressPopWindow != null) {
            if (loadingProgressPopWindow.isShowing()) {
                loadingProgressPopWindow.dismiss();
            }
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        LoggerUtils.getInstance().i("fragment onConfigurationChanged");
        context = getActivity();
    }

    @Override
    public void onStart() {
        super.onStart();
//        changeLanguage(getActivity(), SharePreferenceUtils.getInstance(context).getString("CURRENT_LANGUAGE", "en"));
    }


    public void changeLanguage(Context context, String languageId) {
        if (com.zzp.basepresenter.util.TextUtils.getInstance().isEmpty(languageId)) {
            return;
        }
        Locale locale = null;
        if (languageId.equals("en")) {
            locale = new Locale(languageId, Locale.ENGLISH.getCountry());
        } else if (languageId.equals("ko")) {
            locale = new Locale(languageId, Locale.KOREA.getCountry());
        } else if (languageId.equals("zh")) {
            locale = new Locale(languageId, Locale.CHINA.getCountry());
        }
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        Configuration configuration = resources.getConfiguration();
        configuration.fontScale = 1;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(locale);
        } else {
            configuration.locale = locale;
        }
        resources.updateConfiguration(configuration, metrics);
    }

    //加载动画显示
    public void showLoading(Activity context) {
        if (loadingProgressPopWindow == null) {
            loadingProgressPopWindow = LoadingProgressPopWindow.getInstance(context);
        } else {
            if (loadingProgressPopWindow.isShowing()) {
                loadingProgressPopWindow.dismiss();
            }
        }
        loadingProgressPopWindow.show(context, context.getWindow().getDecorView());
    }

    //加载动画隐藏
    public void hideLoading() {
        if (loadingProgressPopWindow != null) {
            if (loadingProgressPopWindow.isShowing()) {
                loadingProgressPopWindow.dismiss();
            }
        }
    }

}
